package com.tiger.admin.http.apps.category;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiger.admin.Db;
import com.tiger.admin.SaveOperateLog;
import com.tiger.db.entity.AppCategory;
import com.tiger.utils.ResponseUtil;
import com.tiger.utils.Utils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/app/category")
public class AppCategoryController {
    private final Db db;
    private final AppCategoryService appCategoryService;

    public AppCategoryController(Db db, AppCategoryService appCategoryService) {
        this.db = db;
        this.appCategoryService = appCategoryService;
    }

    @GetMapping("options")
    public Object options() {
        return ResponseUtil.successRes(db.appCategory.list(new LambdaQueryWrapper<AppCategory>().select(AppCategory::getId, AppCategory::getName, AppCategory::getParentId).orderByDesc(AppCategory::getSort, AppCategory::getId)));
    }

    @GetMapping("list")
    public Object list() {
        return ResponseUtil.successRes(db.appCategory.list(new LambdaQueryWrapper<AppCategory>().orderByDesc(AppCategory::getSort, AppCategory::getId)));
    }

    @SaveOperateLog("新增服务分类")
    @PostMapping("add")
    public Object add(@RequestBody @Validated AppCategory data, @RequestAttribute("memberId") long memberId) {
        if(db.appCategory.exists(new QueryWrapper<AppCategory>().eq("parent_id", data.getParentId()).eq("name", data.getName()))) {
            return ResponseUtil.failRes("已存在相同的名称");
        }

        if(data.getParentId() == 0) {
            if(data.getRelated() == null || data.getRelated().length == 0) {
                data.setRelated(null);
                data.setAuth(false);
            }else {
                data.setAuth(true);
            }
        }else {
            AppCategory parent = db.appCategory.getOne(new QueryWrapper<AppCategory>().select("auth", "top_id").eq("id", data.getParentId()));
            if(parent == null) return ResponseUtil.failRes();

            data.setRelated(null);
            data.setAuth(parent.isAuth());

            data.setTopId(parent.getTopId() == 0 ? data.getParentId() : parent.getTopId());
        }

        data.setCreatorId(memberId);

        Instant now = Instant.now();

        data.setCreateTime(now.getEpochSecond());
        boolean r = db.appCategory.save(data);

        return r ? ResponseUtil.successRes(data) :  ResponseUtil.failRes();

    }

    @SaveOperateLog("修改服务分类")
    @PostMapping("update/{id}")
    public Object update(@RequestBody @Validated AppCategory data, @PathVariable Integer id, @RequestAttribute("memberId") long memberId) {

        AppCategory row = db.appCategory.getById(id);
        if(row == null) return ResponseUtil.successRes();
        if(data.getName() != null && !data.getName().equals(row.getName())) {
            if(db.appCategory.exists(new QueryWrapper<AppCategory>().eq("parent_id", data.getParentId()).eq("name", data.getName()))) {
                return ResponseUtil.failRes("已存在相同的名称");
            }
        }

        List<Integer> ids = new ArrayList<>(); //子分类的id

        if(!Objects.equals(data.getParentId(), row.getParentId())) { //父分类变了
            Integer newTopId = 0;

            //变成了顶级分类
            if(data.getParentId() == 0) {
                data.setTopId(0);
                if(data.getRelated() != null && data.getRelated().length > 0) {
                    data.setAuth(true);
                    data.setRelated(data.getRelated());
                }else {
                    data.setAuth(false);
                    data.setRelated(null);
                }
                newTopId = id;
            }else { //不是顶级
                data.setRelated(null);
                AppCategory newParent = db.appCategory.getOne(new QueryWrapper<AppCategory>().select("id", "top_id", "auth").eq("id", data.getParentId()));

                newTopId = newParent.getTopId() == 0 ? newParent.getId() : newParent.getTopId();
                data.setAuth(newParent.isAuth());
                data.setTopId(newTopId);


            }

            List<AppCategory> rows = db.appCategory.list(new QueryWrapper<AppCategory>().select("id", "parent_id").eq("top_id", row.getParentId() == 0 ? id : row.getTopId()));
            appCategoryService.querySubCategory(rows, ids, id);


            if(Objects.equals(data.getParentId(), id) || ids.contains(data.getParentId())) {
                return ResponseUtil.failRes("请选择正确的父分类");
            }


            Utils.copyPropertiesIgnoreNull(data, row);
            row.setRelated(data.getRelated());

            if(ids.isEmpty()) {
                boolean r = db.appCategory.updateById(row);
                return r ? ResponseUtil.successRes(row) : ResponseUtil.failRes();
            }

            boolean r = appCategoryService.update(row, ids, newTopId);
            return r ? ResponseUtil.successRes(row) : ResponseUtil.failRes();

        }else { //父分类没有变
            Utils.copyPropertiesIgnoreNull(data, row, "auth", "enable");

            if(row.getParentId() == 0) { //顶级的
                if(data.getRelated() == null || data.getRelated().length == 0) {
                    data.setAuth(false);
                    row.setRelated(null);
                }else {
                    data.setAuth(true);
                }

            }else {
                data.setAuth(false);
                row.setRelated(null);
            }

            if(data.isAuth() != row.isAuth() || data.isEnable() != row.isEnable()) {
                row.setAuth(data.isAuth());
                row.setEnable(data.isEnable());

                if(data.getParentId() == 0 && db.appCategory.exists(new QueryWrapper<AppCategory>().eq("top_id", id))) {
                    boolean r = appCategoryService.update(row, id);
                    return r ? ResponseUtil.successRes(row) : ResponseUtil.failRes();
                }
            }

            boolean r = db.appCategory.updateById(row);
            return r ? ResponseUtil.successRes(row) : ResponseUtil.failRes();

        }


    }

    @SaveOperateLog("删除服务分类")
    @PostMapping("delete/{id}")
    public Object del(@PathVariable long id) {
        AppCategory row = db.appCategory.getOne(new QueryWrapper<AppCategory>().select("id").eq("id", id));
        if(row == null) return ResponseUtil.successRes();

        if(db.appCategory.exists(new QueryWrapper<AppCategory>().eq("parent_id", id))) {
            return ResponseUtil.failRes("存在子分类，不可删除");
        }

        boolean r = db.appCategory.removeById(id);
        return r ? ResponseUtil.successRes() : ResponseUtil.failRes();
    }
}
